from django.shortcuts import render, get_object_or_404
from .models import UserProfile
from .forms import UserProfileForm
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required


@login_required
def show_profile(request):
	"""  查看个人用户资料 """
	return render(request, 'account/profile.html', {'user': request.user})


@login_required
def update_profile(request):
	"""  使用 Form 表单更新用户资料信息 """

	user = request.user
	user_profile = get_object_or_404(UserProfile, user=user)

	if request.method == "POST":
		""" 提交表单 post """
		
		form = UserProfileForm(request.POST)
		
		if form.is_valid():
			# 获取字段
			user.real_name = form.cleaned_data['real_name']
			user.nickname = form.cleaned_data['nickname']
			# 用户头像
			user_profile.avatar = form.cleaned_data['avatar']
			avatar = request.FILES.get('avatar')
			
			with open(avatar.name, 'wb') as f:
				for line in avatar:
					f.write(line)
			user_profile.gender = form.cleaned_data['gender']
			user_profile.phone = form.cleaned_data['phone']
			user_profile.company = form.cleaned_data['company']
			user_profile.department = form.cleaned_data['department']
			user_profile.save()
			
			return HttpResponseRedirect(reverse('userManage:show_profile'))
	else:
		default_data = {
			'real_name': user_profile.real_name,
			'nickname': user_profile.nickname,
			'gender': user_profile.gender,
			'phone': user_profile.phone,
			'company': user_profile.company,
			'department': user_profile.department
		}

		form = UserProfileForm(default_data)
		
		return render(request, 'account/profile_update.html', {'form': form, 'user': user})
